﻿using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartProduction.Domain;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Write.API.Application.Commands.MaterialLists;
using SmartProduction.Write.API.Application.Commands.ProductPlan;
using SmartProduction.Write.API.Application.Commands.WareHouser;
using SmartProduction.Write.API.Application.Commands.WorkFlow;
using SmartProduction.Write.API.Application.Commands.WorNum;
using WorkflowCore.Interface;

namespace SmartProduction.Write.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MangerController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<MangerController> logger;
        private readonly DataDbContext db;
        private readonly IWorkflowHost workflow;

        public MangerController(IMediator mediator, ILogger<MangerController> logger, DataDbContext db,IWorkflowHost workflow)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.db = db;
            this.workflow = workflow;
        }
        [HttpPost("start")]
        public async Task<IActionResult> StartWorkFlow([FromBody] Approval data)
        {
            var id = await workflow.StartWorkflow("MultiLevelApprovalWorkflow", 1, data);
            return Ok(new { WorkFlowId = id });
        }
        /// <summary>
        /// 添加物料
        /// </summary>
        /// <param name="request">实体</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<object>> CreateMaterList(MaterialListCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改物料
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> UpdaterMaterList(MaterListUpdateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 删除物料
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> DeleterMaterList(MaterListDeleteCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 物料类型添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<object>> CreateMarterListType(MaterListTypeCreateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 添加工作流
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<object>> CreateWorkFlow(WorkFlowCreateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 删除工作流
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>返回id</returns>
        [HttpPut]
        public async Task<APIResult<object>> DeleteWorkFlow(WorkFlowDeleteCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修该工作流
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> UpdateWorkflow(WorkFlowUpdateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 添加主生产计划
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]

        public async Task<APIResult<object>> CreateProductPlan(ProductPlanCreateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 删除主生产计划
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回id</returns>
        [HttpPut]
        public async Task<APIResult<object>> DeleteProductPlan(ProductPlanDeleteCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改著生产计划
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> ProductPlanUpdater(ProductPlanUpdateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 添加仓库
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<object>> CreateWareHouser(WareHouserCreateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改仓库
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> UpdateWareHouser(WareHoresUpdateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 删除仓库
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<object>> DeleteWareHores(WareHoresDeleteCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 添加工序
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<object>> CreateWorkNum(WorkNumCreateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改工序管理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> UpdateWorkNum(WorkNumUpdateCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除工序
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<object>> DeleteWorkNum(WorkNumDeleteCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }


        /// <summary>
        /// 导入工作中心管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnums.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<ProductPlan> job = new List<ProductPlan>();

                        foreach (var row in rows)
                        {
                            var plan = new ProductPlan();
                            plan.PlanCode = row.Cell(1).GetValue<string>();
                            plan.PlanName = row.Cell(2).GetValue<string>();
                            plan.PlanDes = row.Cell(3).GetValue<string>();
                            plan.MakeListPerson = row.Cell(4).GetValue<string>();
                            plan.MakeListDepart = row.Cell(5).GetValue<string>();
                            plan.IsStatus = row.Cell(6).GetValue<bool>();
                            plan.ApproveStatus = row.Cell(7).GetValue<int>();

                            // 添加到要插入的列表中
                            job.Add(plan);
                        }
                        await db.AddRangeAsync(job);
                        await db.SaveChangesAsync();
                        result.Code = APIEnums.添加成功;
                        result.Msg = "导入成功";
                        result.data = job.Count.ToString();
                    }
                }
            }
            catch (Exception ex)
            {

                result.Code = APIEnums.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }
    }
}
